package org.l.qiao.connect;

import com.mongodb.*;
import com.mongodb.client.MongoDatabase;
import org.apache.log4j.Logger;

import java.util.Arrays;

public class MongoDB {

    private static final Logger LOGGER = Logger.getLogger(MongoDB.class);
    private String host = "";
    private int port = 27017;
    private String database = "";
    private String username = "";
    private String password = "";


    private MongoClient mongoPool = null;

    public MongoDB() {

    }

    public void setHost(String host) {
        this.host = host;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public void setDatabase(String database) {
        this.database = database;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public boolean init() {
        try {
            MongoCredential credential = MongoCredential.createCredential(username, database, password.toCharArray());
            ServerAddress serverAddress = new ServerAddress(host, port);
            mongoPool = new MongoClient(Arrays.asList(serverAddress), Arrays.asList(credential));
        } catch (Exception e) {
            LOGGER.error("数据库连接异常：" + e);
            return false;
        }
        return true;
    }

    public DBCollection getCollection(String collection) {
        return getDB().getCollection(collection);
    }

    public DB getDB() {
        return mongoPool.getDB(this.database);
    }

    public MongoDatabase getDataBase(){
        return mongoPool.getDatabase(this.database);
    }

    public void close() {
        if (mongoPool != null) {
            mongoPool.close();
        }
        mongoPool = null;
    }
}
